package cn.doitedu.engine;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.HashMap;
import java.util.concurrent.ArrayBlockingQueue;

/**
 * @Author: 深似海
 * @Site: <a href="www.51doit.com">多易教育</a>
 * @QQ: 657270652
 * @Date: 2024/7/22
 * @Desc: 学大数据，上多易教育
 *   静态共享资源持有者
 **/
public class StaticContextV2 {

    private static ArrayBlockingQueue<String> dataQueue;

    private static HashMap<String,String> ruleMap;


    public static ArrayBlockingQueue<String> getDataQueue(){

        if(dataQueue == null ){

            synchronized ("lock"){
                if(dataQueue == null ){
                    dataQueue = new ArrayBlockingQueue<>(100);
                }
            }
        }

        return dataQueue;

    }




    public static HashMap<String,String> getOrRestoreRuleMap() throws IOException, ClassNotFoundException {

        if(ruleMap == null ) {
            synchronized ("ok") {
                if (ruleMap == null) {

                    // 判断快照是否存在，如果存在，则从快照恢复
                    if(FileUtils.getFile("./rule_snapshot/rules.obj").exists()){

                        FileInputStream in = new FileInputStream("./rule_snapshot/rules.obj");
                        ObjectInputStream objIn = new ObjectInputStream(in);

                        ruleMap = (HashMap<String, String>) objIn.readObject();

                    }else {
                        // 否则创建一个新的空的hashmap
                        ruleMap = new HashMap<>();

                    }

                    return ruleMap;
                }

            }
        }

        return ruleMap;
    }
}
